﻿using AutoMail.Models;
using Microsoft.AspNetCore.Mvc;

namespace AutoMail.Controllers
{
    public class EmailTemplatesController : Controller
    {
        private string _birthDayTemplateFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Happy_BirthDay.html");
        private string _anniversaryTemplateFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Happy_nth_Anniversary_Template.html");

        // GET: Open Birthday template editing page
        public async Task<IActionResult> BirthdayMailTemplateEdit()
        {
            // TODO: Read template file to View Model
            var htmlTemplateText = System.IO.File.ReadAllText(_birthDayTemplateFilePath);
            var model = new EmailTemplateViewModel() { HtmlTemplate = htmlTemplateText };

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BirthdayMailTemplateEdit([Bind("Id, HtmlTemplate")] EmailTemplateViewModel emailTemplateViewModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    // TODO: Save the template the file : basedirectory + Happy_BirthDay.html
                    var htmlTemplateText = emailTemplateViewModel.HtmlTemplate;
                    System.IO.File.WriteAllText(_birthDayTemplateFilePath, htmlTemplateText);
                }
                catch (Exception)
                {
                    return NotFound();
                }

                return RedirectToAction("Index", "EmailJobs");
            }

            return View(emailTemplateViewModel);
        }

        // GET: Open Anniversary template editing page
        public async Task<IActionResult> AnniversaryMailTemplateEdit()
        {
            // TODO: Read template file to View Model
            var htmlTemplateText = System.IO.File.ReadAllText(_anniversaryTemplateFilePath);
            var model = new EmailTemplateViewModel() { HtmlTemplate = htmlTemplateText };

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AnniversaryMailTemplateEdit([Bind("Id, HtmlTemplate")] EmailTemplateViewModel emailTemplateViewModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    // TODO: Save the template the file : basedirectory + Happy_nth_Anniversary_Template.html
                    var htmlTemplateText = emailTemplateViewModel.HtmlTemplate;
                    System.IO.File.WriteAllText(_anniversaryTemplateFilePath, htmlTemplateText);
                }
                catch (Exception)
                {
                    return NotFound();
                }

                return RedirectToAction("Index", "EmailJobs");
            }

            return View(emailTemplateViewModel);
        }
    }
}
